package com.oscroll.singleton.lesson;

import com.oscroll.singleton.lesson.LazyThree;
import com.oscroll.singleton.lesson.Seriable;

import java.io.*;
import java.lang.reflect.Constructor;

public class ThreadSafeTest {

    public static void main(String[] args) {
//        int count = 20000;
//        final CountDownLatch latch = new CountDownLatch(count);
//
////        final Set<Hungry> syncSet = Collections.synchronizedSet(new HashSet<Hungry>());
//
//        for (int i = 0; i < count; i++) {
//            new Thread(() -> {
//
////                Hungry.getInstance();
//
//                Object obj = LazyThree.getInstance();
//                System.out.println(System.currentTimeMillis()+""+obj);
//            }).start();
//
//            latch.countDown();
//        }
//
//        try {
//            latch.wait();
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


//        try {
//            Class<?> clazz = LazyThree.class;
//            Constructor[] cs = clazz.getDeclaredConstructors();
//
//            for (Constructor c : cs) {
//                // 反射强制访问
//                c.setAccessible(true);
//                c.newInstance();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        seriableTest();
    }

    private static void seriableTest() {
        Seriable s1 = null;
        Seriable s2 = Seriable.getInstance();

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("Seriable.obj");

            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s2);
            oos.flush();
            oos.close();

            FileInputStream fis = new FileInputStream("Seriable.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            s1 = (Seriable) ois.readObject();
            ois.close();

            System.out.println(s1==s2);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
